#coding:utf-8

import pathlib
from logger import Logger
from logger import set_log_filename
import tool
import datetime

today = str(datetime.date.today())
logger = Logger("Main")
__version__ = (
    pathlib.Path("pyproject.toml")
    .read_text(encoding="utf8")
    .split("version = ")[1]
    .split("\n")[0]
    .strip('"')
)

if __name__ == '__main__':
    tool.logo()
    if not tool.Account.path.exists():
        #没有用户配置，创建
        result = tool.Account.set_ini(tool.Account)
        print(result)
        logger.warning("未找到用户配置")
    mode = str(input('请输入模式\n'
                     '登录：1\n'
                     '修改：2\n'
                     '删除：3\n'
                     '退出：4\n'))
    while mode != '4':
        result1 = tool.Account.obtain_section(tool.Account)
        if result1 == 0:
            #用户配置为空，添加新用户
            result = tool.Account.set_ini(tool.Account)
            print(result)
        if mode == '1':
            section = 'user' + str(input('请输入要登录的用户（输入"user"后的数字即可）'))
            try:
                #获取用户信息
                account_list = tool.Account.obtain_option(tool.Account, section=section)
                logger.info('获取用户信息')
                userid = account_list[0]
                password = account_list[1]
                set_log_filename(today)
                logger.info("\n-----*任务开始执行*-----")
                logger.info(f"Ver. {__version__}")
                spider = tool.ZZIFE(userid=userid, password=password)
                spider.run()
            except Exception as err:
                print("\n-----*程序运行异常退出*-----")
                logger.error("\n-----*程序运行异常退出*-----", exc_info=True)
            except KeyboardInterrupt:
                # 手动中断程序运行
                print("手动中断程序运行")
                logger.info("手动中断程序运行")
            else:
                # 任务执行完毕
                logger.info("\n-----*任务执行完毕, 程序退出*-----")
        elif mode == '2':
            section = 'user' + str(input('请输入要登录的用户（输入"user"后的数字即可）'))
            result2 = tool.Account.modify_ini(tool.Account, section=section)
            print(result2)
        elif mode == '3':
            section = 'user' + str(input('请输入要登录的用户（输入"user"后的数字即可）'))
            result3 = tool.Account.del_ini(tool.Account, section=section)
            print(result3)
        else:
            print('输入错误，请重新输入')
        mode = str(input('请输入模式\n'
                         '登录：1\n'
                         '修改：2\n'
                         '删除：3\n'
                         '退出：4\n'))